﻿using FakeXiecheng.API.DataBase;
using FakeXiecheng.API.Moldes;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using FakeXiecheng.API.Helper;
using FakeXiecheng.API.Dtos;
namespace FakeXiecheng.API.Services
{
    public class TouristRouteRepository:ITouristRouteRepository
    {
        //封装排序字典  IPropertyMapping IPropertyMappingService  PropertyMapping PropertyMappingService PropertyMappingValue
        private readonly AppDbContext _context;
        private readonly IPropertyMappingService _propertyMappingService;
        public TouristRouteRepository(
            AppDbContext context,
            IPropertyMappingService propertyMappingService
            )
        {
            _context = context;
            _propertyMappingService = propertyMappingService;
        }
        //返回路线数据
        public async Task<TouristRoute> GetToruistRouteAsync(Guid touristRouteId)
        {
            return await _context.TouristRoutes.Include(t => t.TouristRoutePictures).FirstOrDefaultAsync(n=>n.Id==touristRouteId);
        }
        // public async Task<IEnumerable<TouristRoute>> GetTouristRoutesAsync(
        //    string keyword,
        //    string ratingOperator,
        //    int? ratingValue,
        //    int pageSize,
        //    int pageNumber
        //)
        public async Task<PaginationList<TouristRoute>> GetTouristRoutesAsync(
        string keyword,
        string ratingOperator,
        int? ratingValue,
        int pageSize,
        int pageNumber,
        string orderBy
        )
        {
            IQueryable<TouristRoute> result = _context
                .TouristRoutes
                .Include(t => t.TouristRoutePictures);
            if (!string.IsNullOrWhiteSpace(keyword))
            {
                keyword = keyword.Trim();
                result = result.Where(t => t.Title.Contains(keyword));
            }
            if (ratingValue >= 0)
            {
                result = ratingOperator switch
                {
                    "largerThan" => result.Where(t => t.Rating >= ratingValue),
                    "lessThan" => result.Where(t => t.Rating <= ratingValue),
                    _ => result.Where(t => t.Rating == ratingValue),
                };
            }
            //排序  
            if (!string.IsNullOrWhiteSpace(orderBy))
            {
                var touristRouteMappingDictionary = _propertyMappingService
                    .GetPropertyMapping<TouristRouteDto, TouristRoute>();

                result = result.ApplySort(orderBy, touristRouteMappingDictionary);
            }
            //if (!string.IsNullOrWhiteSpace(orderBy))
            //{
            //    //if(orderBy.ToLowerInvariant() =="originalprice")
            //    //{
            //    //    result=result.OrderBy(t => t.OriginalPrice);
            //    //}
            //    //System.Linq.Dynamic.Core 进行排序
            //    var touristRouteMappingDictionary = _propertyMappingService.GetPropertyMapping
            //        <TouristRouteDto, TouristRoute>();//路线字典映射
            //    result=result.ApplySort(orderBy, touristRouteMappingDictionary);//ApplySort --Helper-IQueryableExtensions
            //}
            //pagination
            //skip
            //var skip=(pageNumber-1)*pageSize;
            //result=result.Skip(skip);
            ////以pagesize为标准显示一定量的数据
            //result=result.Take(pageSize);
            // include vs join
            //return await result.ToListAsync();
            return await PaginationList<TouristRoute>.CreateAsync(pageNumber, pageSize, result);
        }

        //public IEnumerable<TouristRoute> GetTouristRoutes()
        //{
        //    //include vs join 两个表链接
        //    return _context.TouristRoutes.Include(t=>t.TouristRoutePictures);
        //}
        public async Task<bool> TouristRouteExistsAsync(Guid touristRouteId)
        {
            return await _context.TouristRoutes.AnyAsync(t => t.Id == touristRouteId);
        }

        public async Task<IEnumerable<TouristRoutePicture>> GetPicturesByTouristRouteIdAsync(Guid touristRouteId)
        {
            return await _context.TouristRoutesPicture
                .Where(p => p.TburistRouteId == touristRouteId).ToListAsync();
        }
        public async Task<TouristRoutePicture> GetPictureAsync(int pictureId) 
        { 
          return await _context.TouristRoutesPicture.Where(p=>p.Id == pictureId).FirstOrDefaultAsync();
        }
        //批量返回一组数据
        public async Task<IEnumerable<TouristRoute>> GetTouristRoutesByIDListAsync(IEnumerable<Guid> ids)
        {
            return await _context.TouristRoutes.Where(t=>ids.Contains(t.Id)).ToListAsync();
        }
        public void AddTouristRoute(TouristRoute touristRoute)
        {
            if (touristRoute == null)
            {
                throw new ArgumentNullException(nameof(touristRoute));
            }
            _context.TouristRoutes.Add(touristRoute);
            //_context.SaveChanges();
        }

        public void AddTouristRoutePicture(Guid touristRouteId, TouristRoutePicture touristRoutePicture)
        {
            if (touristRouteId == Guid.Empty)
            {
                throw new ArgumentNullException(nameof(touristRouteId));
            }
            if (touristRoutePicture == null)
            {
                throw new ArgumentNullException(nameof(touristRoutePicture));
            }
            touristRoutePicture.TburistRouteId= touristRouteId;
            _context.TouristRoutesPicture.Add(touristRoutePicture);
        }

        public void DeleteTouristRoute(TouristRoute touristRoute)
        {
            _context.TouristRoutes.Remove(touristRoute);
        }
        public void DeleteTouristRoutePicture(TouristRoutePicture picture)
        {
            _context.TouristRoutesPicture.Remove(picture);
        }
        //批量删除数据
        public void DeleteTouristRoutes(IEnumerable<TouristRoute> touristRoutes)
        {
            _context.TouristRoutes.RemoveRange(touristRoutes);
        }
        //实现购物车接口
        public async Task<ShoppingCart> GetShoppingCartByUserId(string userId)
        {
            return await _context.ShoppingCarts
               .Include(s => s.User)
               .Include(s => s.ShoppingCartItems).ThenInclude(li => li.TouristRoute)
               .Where(s => s.UserId == userId)
               .FirstOrDefaultAsync();
            //return await _context.ShoppingCarts
            // .Include(s => s.User)//将ShoppingCart和User表链接
            // .Include(s => s.ShoppingCartItems).ThenInclude(li => li.TouristRoute)//将lineitem表链接
            // .Where(s => s.UserId == userId)//过滤数据
            // .FirstOrDefaultAsync();//唯一的购物车
        }
        //实现添加购物车接口
        public async Task CreateShoppingCart(ShoppingCart shoppingCart)
        {
            await _context.ShoppingCarts.AddAsync(shoppingCart);
        }

        public async Task AddShoppingCartItem(LineItem lineItem)
        {
            await _context.LineItems.AddAsync(lineItem);
        }
        //获取购物车信息
        public async Task<LineItem> GetShoppingCartItemByItemId(int lineItemId)
        {
            return await _context.LineItems
                .Where(li => li.Id == lineItemId)
                .FirstOrDefaultAsync();
        }
        //删除单一资源
        public  void DeleteShoppingCartItem(LineItem lineItem)
        {
             _context.LineItems.Remove(lineItem);
        }

        public async Task<bool> SaveAsync()
        {
            return (await _context.SaveChangesAsync() >= 0);
        }
        //实现批量删除
        public async Task<IEnumerable<LineItem>> GeshoppingCartsByIdListAsync(
           IEnumerable<int> ids)
        {
            return await _context.LineItems
                .Where(li => ids.Contains(li.Id))
                .ToListAsync();
        }


        public void DeleteShoppingCartItems(IEnumerable<LineItem> lineItems)
        {
            _context.LineItems.RemoveRange(lineItems);
        }
        //添加订单
        public async Task AddOrderAsync(Order order)
        {
            await _context.Orders.AddAsync(order);
        }

        //public async Task<IEnumerable<Order>> GetOrdersByUserId(string userId)
        //{
        //    return await _context.Orders.Where(o => o.UserId == userId).ToListAsync();
        //}
        public async Task<PaginationList<Order>> GetOrdersByUserId(string userId,int pageSize,int pageNumber)
        {
            //return await _context.Orders.Where(o => o.UserId == userId).ToListAsync();
            IQueryable<Order> result = _context.Orders.Where(o => o.UserId == userId);
            return await PaginationList<Order>.CreateAsync(pageNumber, pageSize, result);
        }

        public async Task<Order> GetOrderById(Guid orderId)
        {
            return await _context.Orders
                .Include(o => o.OrderItems).ThenInclude(oi => oi.TouristRoute)//获得订单内产品列表
                .Where(o => o.Id == orderId)
                .FirstOrDefaultAsync();
        }

    }
}
